package com.niiwoo.civet.trade.listener;

import com.alibaba.dubbo.config.annotation.Reference;
import com.niiwoo.civet.trade.constant.MqConstant;
import com.niiwoo.civet.trade.dto.request.contract.WithholdContractSignMQDTO;
import com.niiwoo.civet.trade.service.contract.WithholdContractDubboService;
import com.niiwoo.tripod.provider.exception.BizException;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class FadadaContractListener {

    /*@Autowired
    private RepaymentLocalService repaymentLocalService;**/

    @Reference(version = "1.0.0")
    private WithholdContractDubboService withholdContractDubboService;

    /**
     * 还款服务委托书签署监听器
     * @param withholdContractSignMQDTO
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(queues = {MqConstant.FADADA_WITHHOLD_CONTRACT_QUEUE})
    public void withholdContractSign(WithholdContractSignMQDTO withholdContractSignMQDTO, Message message, Channel channel) {
        String userId = withholdContractSignMQDTO.getUserId();
        Long projectId = withholdContractSignMQDTO.getProjectId();
        log.info("withholdContractSign.contractGenerateAndSign start,userId={}",userId);
        Boolean isAck = true;
        try {
            withholdContractDubboService.contractGenerateAndSign(withholdContractSignMQDTO.getUserId(), withholdContractSignMQDTO.getProjectId());
            log.info("withholdContractSign.contractGenerateAndSign success,userId={}",userId);
        } catch (BizException e) {
            log.error("withholdContractSign BizException,userId={}", userId,e);
        } catch (Exception e) {
            log.error("withholdContractSign Exception,userId={}", userId,e);
            isAck = false;
            try {
                Thread.sleep(10 * 1000 * 60 );
            } catch (Exception expect) {
            }
        } finally {
            try {
                log.info("withholdContractSign.isAck={},userId={}",isAck,userId);
                if (isAck) {
                    log.info("withholdContractSign.basicAck start,userId={}",userId);
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                    log.info("withholdContractSign.basicAck end,userId={}",userId);
                } else {
                    log.info("withholdContractSign.basicNack start,userId={}",userId);
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
                    log.info("withholdContractSign.basicNack end,userId={}",userId);
                }
            } catch (IOException e) {
                log.error("withholdContractSign ack error,userId={}",userId,e);
            }
        }
    }

}
